<?php
	/**
	 * 实现多模块复合请求分发
	 *
	 */
	class ApiAction {
		
		public static $checkSign = false;// 检查签名开关


		private $request = null;
		public static $actionList = array();
		
		//功能模块划分
		public static $moduleConfig = array(
		    9 => 'ApiCommonAction',
            10 => 'ApiUserAction',
            20 => 'ApiDataAction',
		);
		
		/**
		 * 根据cmd返回相应功能模块处理对象
		 * @return DispatchBasic
		 */
		public static function getActionInstance($command, Array $cmdParams, Request $request) {
			$module = floor(intval($command) / 1000);
			
			if(!isset(self::$moduleConfig[$module])) {
				return false;
			}
			
			if(!isset(self::$actionList[$module])) {
				$action = self::$moduleConfig[$module];
				self::$actionList[$action] = new $action($request);
			}

			return self::$actionList[$action];
		}
		/**
		 * 按照复合响应结果输出错误状态码并结束
		 * @param int $statusCode
		 */
		public static function errorExit($statusCode) {
			$status = Status::getStatusCode($statusCode);
			if(empty($status)){
				$status = "{$statusCode}:undefine status code";
			}
			exit(ResponseUtil::createResponseWithCallback($status));
		}

        public function checkSign() {
            $params = $this->request->requestParams();
            $checkSign = md5($_REQUEST['userid'] . $_REQUEST['channelid'] . $_REQUEST['vc'] . $_REQUEST['unixtime'] . $params['params']);
            return strtoupper($params['sign'])===strtoupper($checkSign);
        }

        /**
		 * 程序入口
		 */
		public function doIndex(){
			try{
				$request = $this->request = new Request();
				$request->init();
				if(self::$checkSign && !$this->checkSign()) {
					self::errorExit(Status::ERROR_CHECK_FAIL);
				}

				$request->initComplexParams();
				$params = $request->requestParams();

				$interfaceList = null;
				if($request->isComplex()){
					$interfaceList = $request->cmdRequestParams();
				}else{
					//未设置接口
					if(!isset($params['cmd']) || $params['cmd'] < 1){
						self::errorExit(Status::ERROR_INTERFACE_NOT_EXIST);
					}
				}

                //定义全局变量保存当前渠道信息
//                global $extChannel;
//                $channelCache = new ChannelCache();
//                $extChannel = $channelCache->getextChannelinfoByChannelidCache($params['channelid']);
//
				//循环处理接口请求，并且按照复合响应结果返回
				$resList = array();
				foreach($interfaceList as $command => $cmdParams) {

					// 接口分发
					$action = self::getActionInstance($command, $cmdParams, $this->request);
					if (!$action) {
						$status = Status::getStatusCode(Status::ERROR_INTERFACE_NOT_EXIST);
					}else {
						$status = $action->dispatch($command);
					}
					
					if(!isset($status['data'])){
						$status['data'] = null;
					}
					$status['cmd'] = $command;
					$resList[] = $status;
				}

				exit(ResponseUtil::createResponseWithCallback($resList));
			}catch(Exception $e){
				echo $e->getMessage();
				self::errorExit(Status::ERROR_SYSTEM);
			}
		}
		
	}